package com.java2104.controller;

import com.java2104.entity.User;
import com.java2104.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/modifyPassword")
    @ResponseBody
    public Map modifyPassword(String newPassword,String oldPassword,
                              @SessionAttribute("loginUser") User user){
        return userService.modifyPassword(user,oldPassword,newPassword);
    }

    @PostMapping("/update")
    @ResponseBody
    public Map update(User user){
        return userService.update(user);
    }

    @GetMapping("/showUpdateUser")
    public void showUpdateUser(Model model,Integer id){
        model.addAttribute("user",userService.get(id));
    }

    //客户端传输的是一个JSON字符串
    @RequestMapping(path = "/delete",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    //@RequestBody的作用是将客户端传输的JSON字符串转换成Java集合
    public void delete(@RequestBody(required = false) List<Integer> ids){
        userService.delete(ids);//执行删除操作
    }
    @GetMapping({"/user","/"})
    public String user(){
        return "user";
    }
    @GetMapping("/showAddUser")
    public String showAddUser(){
        return "showAddUser";
    }
    @PostMapping("/add")
    @ResponseBody
    public Map add(User user){
        /*Map ret = new HashMap();
        ret.put("status","success");*/
        return userService.save(user);
        /*return ret;*/
    }
    @RequestMapping("/list")
    @ResponseBody
    public List<User> list(String loginname,Integer role){
        return userService.getList(loginname,role);
    }
}
